package com.luna.servlets;


import com.luna.beans.User;
import com.luna.service.UserService;
import com.luna.serviceImpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(
    name = "LoginServlet",
    urlPatterns = "/LoginServlet"
)
public class LoginServlet extends HttpServlet {

    public LoginServlet() {}

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html charset=UTF-8");
        UserService userService = new UserServiceImpl();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = userService.login(username, password);
        if (user != null) {
            req.getSession().setAttribute("user", user);
            req.getRequestDispatcher("/RoleShunt").forward(req, resp);
        } else {
            req.getRequestDispatcher("login-failed.jsp").forward(req, resp);
        }
    }
}
